/*
 * DA1.asm
 *
 *  Created: 2/10/2015 11:04:52 AM
 *   Author: smith760

Darius Smith
CPE 301 - Dr. Venki
Assignment 1 DA1

a.
Store 25 numbers starting from the RAMEND location. Capture the lower 8bits of the 
RAM MIDDLE = (RAMBEGIN + RAMEND)/2 address and use them as your values. You can 
increment or decrement from RAM MIDDLE location to get thesubsequent 24 numbers. Make
sure the sum is not greater than 16-bits. Use the X/Y/Z registers to fill up the stack
of 25 numbers.
b.
Parse through the 25 numbers and add all numbers divisible by 7 and place the
result in R20:21.
c.
Parse through the 25 numbers and add all numbers divisible by 3 and place the result in
R23:24. Parsing of the numbers for task b and c has to be done simultaneously.
d.
Determine the execution time @ 16MHz/#cycles of your algorithm using the simulation. 
 */ 


//Used Registers r0,r3,r7,r16,r17,r18,r19,r20,r21,r22,r23,r24,26,r27,r28,r31

.def cnt = r22
.def loader = r31
.def zero = r0
.def three = r3
.def seven = r7

ldi		r31, 0
mov		r0, r31
ldi		r31, 3
mov		r3, r31
ldi		r31, 7
mov		r7, r31

ldi		r16, low(ramend)	//lower 8 bits of the ramend location is strored into 16bit register r16
ldi		r17, high(ramend)	//upper 8 bits of the ramend location is strored into 16bit register r17
ldi		r18, 0x00			// ram begin is not a fixed value and doesnt have a reserved word
ldi		r19, 0x01			// rambegin's address is 0x0010 r18 and r19 holds the low and high sections of it

add		r16, r18			//holds the lower sum of ramend + rambegin
adc		r17, r19			//(add with carry) holds the upper sum of ramend + rambegin

lsr		r17					//shifts all bits right (divides by 2)
ror		r16					//rotates right and checks the LSB from r17
							// now i have Middle location stored in r17+r16

mov		xl, r16				//loads the bottom half of the middle address into xl
mov		xh, r17				//loads the top half of the middle address into xh

storeLoop:
st		x, r16				//store the value of whats in the r16 register and save it to xlow
inc		r16					//increments to the next value after Ram Middle
dec		xl					//sets X up to the next memory location 
inc		cnt
cpi		cnt, 25
brlt	storeLoop
inc		xl
ldi		cnt, 0
	parseLoop: 
ld		r18, x
cp		r18, three
brlo	after3
	loop3:				
sub		r18, three				//subtract 3 from value until its less than 3
cp		r18, three				//compare value to 3 to check if we have to loop back
brsh	loop3				//loop arount if same or higher than 3
cpi		r18, 0				//compare r20 to be same or equal to 0				
brne	after3				//if = 0 go to next line if not go to after3
ld		r19, x				//add x to the running sum of numbers divisible by 3
add		r24, r19
adc		r23, zero
	after3:


ld		r18, x
cp		r18, seven
brlo	after7
	loop7:
sub		r18, seven
cp		r18, seven
brsh	loop7
cpi		r18, 0
brne	after7
ld		r19, x
add		r21, r19
adc		r20, zero
	after7:

inc		cnt
inc		xl
cpi		cnt, 26
brlt	parseLoop

forever:
jmp forever